"""
lviewer.tools.console

Support for calling external programs
"""
import subprocess

class ToolFailure( Exception ):
    def __init__(self, desc, stdout, stderr):
        msg = "%s\n%s\n%s" % (desc, stdout, stderr)
        Exception.__init__(self, msg)

class Tool( object ):
    def __init__(self, args):
        print args
        self.process = subprocess.Popen(args, 
            stdin = subprocess.PIPE,
            stdout = subprocess.PIPE,
            stderr = subprocess.PIPE
        )
        self.stdin = self.process.stdin
        self.stdout = None
        self.stderr = None

    def finish(self):
        self.stdout, self.stderr = self.process.communicate()
        if self.process.returncode != 0:
            raise ToolFailure("Tool failure", self.stdout, self.stderr)

def execute(args):
    return Tool(args)
    
